<?php

namespace app\controllers\h5;

use app\award\Award;
use app\controllers\h5\base\H5Controller;
use app\controllers\h5\services\User;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\TransferStore;
use app\models\user\UserLevel;
use app\models\UserStore;
use app\models\UserStoreLog;

class StoreController extends H5Controller
{
    public function actionCounter()
    {
        $model = UserStore::findOne(['user_id' => $this->user->id]);
        if (!$model) {
            $model = new UserStore();
            $model->user_id = $this->user->id;
            $model->save();
        }

        $model['num'] = intval($model['num']);

        // 可提商品
        $products = Product::find()
            ->where(['status' => Product::$statusMapping['OK']])
            ->andWhere(['is_extract' => 1])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->with(['mainImage'])
            ->asArray()
            ->all();

        return $this->successEncode([
            'model' => $model->toArray(),
            'products' => $products
        ]);
    }

    public function actionList()
    {
        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $type = intval($this->post('type',1));

        $query = UserStoreLog::find()
            ->where(['user_id' => $this->user->id])
            ->andWhere(['type' => $type]);

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->asArray()
            ->all();

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }

    // 提货
    public function actionExtract()
    {
        $num = intval($this->post('num', 0));
        $address_id = intval($this->post('address_id', 0));

        $products = $this->post('products');
        // var_dump($products);exit;

        // 新的数量
        $num = 0;
        foreach ($products as $product) {
            $num += $product['num'];
        }

        // var_dump($num);exit;

        if (!$num) {
            return $this->fail('数量错误!!');
        }
        if (!$address_id) {
            return $this->fail('地址错误!!');
        }

        // var_dump($address_id, $num);exit;


        $transaction = \Yii::$app->db->beginTransaction();

        try {
            $store = UserStore::findOne(['user_id' => $this->user->id]);

            if (!$store || $store->num < $num) {
                throw new \Exception('操作错误!!');
            }

            // 创建订单
            $order = new Order();
            $order->sn = Order::generateSn();
            // 云仓提供(也对应数量)
            $order->is_extract = $num;
            $order->user_address = $address_id;
            $order->user_id = $this->user->id;
            $order->total_pay = 0;
            $order->request_params = '';
            $order->status = Order::$statusMapping['PAID'];
            $order->total_quantity = $num;
            $r=$order->save();
            if (!$r) {
                throw new \Exception($order->getFirstError());
            }

            // 商品详情[直接用最新一个上架的商品], 否则物流会有问题
            // $from_item = null;
            // $product = Product::find()
            //     ->where(['status' => 1])
            //     ->orderBy(['id' => SORT_DESC])
            //     ->one();

            // 新的
            foreach ($products as $product) {
                if ($product['num'] == 0) {
                    continue;
                }
                $item = new OrderItem();
                $item->order_id = $order->id;
                $item->quantity = $product['num'];
                $item->product_id = $product['id'];
                $item->product_sku_id = 0;
                $item->selected_sku_value = '';
                $item->selected_sku_text = '';
                $item->freight = 0;
                $item->price = 0;
                $item->score = 0;
                // is express
                $item->is_express = 1;
                $r = $item->save();
            }

            // 佣金
            // new Award($order, false);


            // 减云仓
            UserStoreLog::addLog($this->user->id, $store->num, -$num, $store->num - $num,
                '提货', 3);

            $store->num -= $num;
            $store->save();



            $transaction->commit();
            return $this->success();
        } catch (\Exception $e) {

            $transaction->rollBack();
            return $this->fail($e->getMessage() . ' ' . $e->getLine(). ' ' . $e->getFile());
            return $this->fail($e->getMessage());
        }

        // return $this->success();
    }

    // 进货日志
    public function actionReferrerLog()
    {
        $list = TransferStore::find()
            ->where(['received_id' => $this->user->id])
            ->orderBy(['id' => SORT_DESC])
            ->asArray()
            ->all();

        return $this->successEncode(['list' => $list]);
    }

    // 我的供货商
    public function actionGetReferrer()
    {
        $total = 0;

        $id = \app\models\user\User::find()
            ->where(['id' => $this->user->id ])
            ->select(['referrer_id'])
            ->scalar();
        if ($id) {
            $store = UserStore::findOne(['user_id' => $id]);
            if ($store) {
                $total = $store->num;
            }
        }

        return $this->successEncode(['total' => $total]);
    }

    // 保存进货
    public function actionSaveReferrer()
    {
        $sum = $this->post('sum');

        $id = \app\models\user\User::find()
            ->where(['id' => $this->user->id ])
            ->select(['referrer_id'])
            ->scalar();
        if ($id) {
            $store = UserStore::findOne(['user_id' => $id]);
            if ($store) {

                if ($store->num < $sum) {
                    return $this->fail('数量错误');
                }

                // 操作进货
                $transaction = \Yii::$app->db->beginTransaction();
                try {

                    $store->num -= $sum;
                    $store->save();
                    UserStoreLog::addLog($id, $store->num, -$sum, $store->num - $sum,
                        '出货', 2);

                    $log = new TransferStore();
                    $log->send_id = $id;
                    $log->received_id = $this->user->id;
                    $log->sum = $sum;
                    $log->status = 0;
                    $log->save();

                    $transaction->commit();
                    return $this->success();

                } catch (\Exception $e) {

                    $transaction->rollBack();
                    return $this->fail('操作错误');

                }

            }
        }

        return $this->fail('操作错误');
    }

    // 出货
    public function actionGetSellList()
    {
        $list = TransferStore::find()
            ->where(['send_id' => $this->user->id])
            ->orderBy(['id' => SORT_DESC])
            ->asArray()
            ->all();

        return $this->successEncode(['list' => $list]);
    }

    // 审核
    public function actionSellCheck()
    {
        $id = $this->post('id');

        $transaction = \Yii::$app->db->beginTransaction();
        try {

            $model = TransferStore::findOne(['id' => $id]);
            if (!$model) {
                throw new \Exception('错误');
            }

            $model->status = 1;
            $model->save();

            // 购买人的云仓
            $store = UserStore::findOne(['user_id' => $model->received_id]);
            if (!$store) {
                $store = new UserStore();
                $store->user_id = $model->received_id;
                $store->num = 0;
            }
            $store->num += $model->sum;
            $store->save();

            UserStoreLog::addLog($model->received_id, $store->num, $model->sum, $model->sum + $store->num,
                '进货', 1);

            // 升级处理
            $levels = UserLevel::find()
                ->where(['>=', 'store', 1])
                ->orderBy(['store' => SORT_DESC])
                ->all();
            $u = \app\models\user\User::findOne(['id' => $model->received_id]);
            foreach ($levels as $level) {
                if ($model->sum >= $level->store) {
                    if ($u->level < $level->value) {
                        $u->level = $level->value;
                        $u->save();
                        break;
                    }
                }
            }

            $transaction->commit();
            return $this->success();

        } catch (\Exception $e) {

            $transaction->rollBack();
            return $this->fail('操作错误');

        }
    }

    // 驳回
    public function actionSellReject()
    {
        $id = $this->post('id');

        $transaction = \Yii::$app->db->beginTransaction();
        try {

            $model = TransferStore::findOne(['id' => $id]);
            if (!$model) {
                throw new \Exception('错误');
            }

            $model->status = -1;
            $model->save();

            // 出货人
            $store = UserStore::findOne(['user_id' => $model->send_id]);
            $store->num += $model->sum;
            $store->save();

            UserStoreLog::addLog($model->send_id, $store->num, $model->sum, $store->num + $model->sum,
                '驳回进货', 1);

            $transaction->commit();
            return $this->success();

        } catch (\Exception $e) {

            $transaction->rollBack();
            return $this->fail('操作错误');

        }
    }
}